package com.jf3q.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.admin.dto.BannerDto;
import com.jf3q.common.domain.EduBanner;

import com.jf3q.common.service.BannerService;
import com.jf3q.common.service.UploadVideoService;
import com.jf3q.common.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/banner")
public class BannerController {
    @Autowired
    BannerService bannerService;
    @Autowired
    UploadVideoService uploadVideoService;

    @PostMapping("/getAllBanner")
    @Operation(summary = "查询全部轮播图")
    public ResultVo getAllBanner(@RequestBody BannerDto bannerDto){
        Page<EduBanner> page = bannerService.page(new Page<>(bannerDto.getPageNum(), bannerDto.getPageSize()));
        return ResultVo.success("",page);
    }

    @PostMapping("/bannerAddOrUpd")
    @Operation(summary = "轮播图新增或修改")
    public ResultVo bannerAddOrUpd(EduBanner eduBanner, MultipartFile file){
        try {
            if (file!=null && !file.isEmpty()){
                String url = uploadVideoService.upload(file, "banner");
                eduBanner.setImageUrl(url);
                if (StringUtils.hasText(eduBanner.getId())){
                    EduBanner banner = bannerService.getById(eduBanner.getId());
                    uploadVideoService.delOssFile(banner.getImageUrl());
                }
            }
            bannerService.saveOrUpdate(eduBanner);
        } catch (Exception e) {
            return ResultVo.error("操作失败");
        }
        return ResultVo.success();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "轮播图删除")
    @Transactional
    public ResultVo bannerDelete(@PathVariable String id){
        try {
            EduBanner eduBanner = bannerService.getById(id);
            uploadVideoService.delOssFile(eduBanner.getImageUrl());
            bannerService.removeById(id);
            return ResultVo.success();
        } catch (Exception e) {
            return ResultVo.error("操作失败");
        }
    }
}
